class Router {

    static getInstance() {
        if(!Router.instance){
            Router.instance = new Router();
        }
        return Router.instance;
    }

    add()
    {
        CONFIG.keydownAddRouterBtn = true;
        CONFIG.drawingRouterEdgePoints=[];
        setRouteName();
    }

    /**
     * 1)格式化ScheduleTime为int类型
     * 2）按照SchudeuleTime 开始时间升序，结束时间升序
     * 3）Route信息写入队列任务
     * @param id
     */
    calculateRouterInfo( routerId )
    {
        this.getCustmoerArriverStarTimeAndArriverEndTime( routerId )
        this.optimizeOrderpoints( routerId );
        let points =OBJECT.routerPonits[routerId];
        if( typeof points.points !='undefined')
         {

                 OBJECT.requestRoutePromiseHandle.push({
                        points:OBJECT.routerPonits[routerId].points,
                        routerId:routerId,
                        color:OBJECT.routersBgColorMap[routerId],
                        locked:false,
                        method:Router.getInstance().calculateRoute
                  });

                OBJECT.requestRouteStatus.set( routerId ,'pending');
           }


    }

    /**
     * 计算Router 请求API显示地图
     * @param routers
     * @param routerId
     * @param color
     * @param resovle
     * @param reject
     */
    calculateRoute( routers ,routerId, color ,resovle , reject) {
        var _this = this;
        Router.getInstance().setData( routerId ,routers );
        let len = routers.length;
        let  end_piont = routers[len-1];
        let directionsService = new google.maps.DirectionsService;
        OBJECT.directionsDisplay[routerId] = new google.maps.DirectionsRenderer({
            "routerId":routerId ,   //地图唯一表示，对应数据库主键
            "routers":routers,
            suppressMarkers : true,
            polylineOptions: {
                strokeColor: color,
                strokeOpacity:0.7
            }
        });

        directionsService.route({
            origin:{lat:Number(CONFIG.wareHouseCenter.lat) , lng:Number(CONFIG.wareHouseCenter.lng)},
            destination: {lat: parseFloat(end_piont.lat) , lng:parseFloat(end_piont.lng) },
            travelMode: 'DRIVING',
            optimizeWaypoints:false,
            waypoints:_this.getWayPionts(routers)
        }, function(response, status) {
            console.log(routerId,status,new Date().toLocaleTimeString())
            if (status === 'OK') {
                OBJECT.directionsDisplay[routerId].setDirections(response);
                Router.getInstance().setRouteSchedule( routerId );
                OBJECT.requestRouteStatus.set( routerId ,'success');
                OBJECT.routerPonits[routerId].UpdateStatus = false;
                Hook.getInstance().doAction('afterCompleteRouteSchedule');
                resovle('SUCCESS');

            } else if( status=='MAX_WAYPOINTS_EXCEEDED') {
                colseLoading();
                delete OBJECT.directionsDisplay[routerId];
                reject(status);
                $.Pro('最大不能超过24个站点');
            }
        });


    }

    /**
     * 计算到达客户地点的最早时间和最晚时间
     * @param routerId
     */
    getCustmoerArriverStarTimeAndArriverEndTime(routerId)
    {
        OBJECT.routerPonits[routerId].points.forEach( function ( value , index) {
                let t =OBJECT.routerPonits[routerId].points[index].ScheduleTime.split('--');
                 OBJECT.routerPonits[routerId].points[index].arriveStartTimeString = Number(t[0].replace(':',''));
                 OBJECT.routerPonits[routerId].points[index].arriveEndTimeString  = Number(t[1].replace(':',''));

        })

    }

    /**
     * 路线最优排序
     * @param routerId
     */
    optimizeOrderpoints (routerId)
    {
           if( CONFIG.optimizeOrderpoints[routerId])
           {
               console.log('haha')
               let points = OBJECT.routerPonits[routerId].points;
               points.sort(function (a, b) {
                   return SortByProps(a, b, { "arriveStartTimeString": "ascending", "arriveEndTimeString": "ascending" });
               });
               OBJECT.routerPonits[routerId].points = points;
               CONFIG.optimizeOrderpoints[routerId] = false;

           }
    }
    /**
     * 获取途经点
     * @param waypoints
     * @returns {*}
     */
    getWayPionts (waypoints) {

        if(waypoints.length==1){   //不存在途经点
            return [];
        }else{
            var json=[];
            for(var i=0;i < waypoints.length; i++ ){
                var arr={};
                var temp={};
                temp.lat= parseFloat(waypoints[i].lat);
                temp.lng= parseFloat(waypoints[i].lng);
                arr.location = temp;
                json.push(arr);

            }
            return json;
        }
        return wayPointsJson;
    }
    /**
     * 设置数据
     * @param routerId
     * @param data
     */
    setData(routerId , data){
        OBJECT.routerPonits[routerId] = OBJECT.routerPonits[routerId] || {}
       // OBJECT.routerPonits[routerId].vehicleId = OBJECT.routerPonits[routerId].vehicleId || null;   //设置默认值
       // OBJECT.routerPonits[routerId].points = data;
      //  OBJECT.routerPonits[routerId].schedule =  null;
        OBJECT.routerPonits[routerId].UpdateStatus = false;

    }
    /**
     * 设置路线每个点之间的时间和路程
     * @param routerId
     */
    setRouteSchedule ( routerId ) {
        let wayPonits = OBJECT.directionsDisplay[routerId].getDirections();
        let schedule =  wayPonits.routes[0].legs;
        let ret = [];
        schedule.forEach(function ( value , index ) {
            let t ={distance:value.distance,duration:value.duration};
            ret.push( t );
        })
        OBJECT.routerPonits[routerId].schedule = ret;
    }
    /**
     * 设置当前操作的路由id
     * @param routerId
     */
    setCurrentRouterId( routerId){
        CONFIG.currentOpearateRouterId = routerId;
    }
    /**
     * 获取当前操作的路由id
     * @param routerId
     */
    getCurrentRouterId(){
        return CONFIG.currentOpearateRouterId || null;
    }

    /**
     * 删除一个区域和他的属性
     * @param routerId
     */
    removeRouter(routerId)
    {
        delete OBJECT.routerPonits[routerId];
        delete OBJECT.dispalyPositonList[routerId];
        delete OBJECT.routerEdgePoints[routerId];
        delete OBJECT.directionsDisplay[routerId];
    }

    /**
     * 设置Router的更新状态
     * @param routerId
     * @param status
     */
    setRouterUpdateStatus( routerId, status)
    {
          return OBJECT.routerPonits[routerId].UpdateStatus = status;
    }

    /**
     * 把路线的ABCDEFG顺序改成123456
     * @param position
     * @param i
     * @returns {google.maps.Marker}
     */
    addMarkerOnRouter(position, i , routerId) {
        OBJECT.numberMarkerOnRouter.push( new google.maps.Marker({
            // @see http://stackoverflow.com/questions/2436484/how-can-i-create-numbered-map-markers-in-google-maps-v3 for numbered icons
            icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + i + '|0095ff|FFF',
            position: position,
            map: map,
        }))
    }

    /**
     * 隐藏路线的数字market
     * @param position
     * @param i
     * @returns {google.maps.Marker}
     */
    hideMarkerOnRouter( routerId) {
        for (let index in OBJECT.numberMarkerOnRouter)
        {
             OBJECT.numberMarkerOnRouter[index].setMap( null );
        }
    }
    /**
     * 在路线的显示ABCDEFG改成123456
     * @param position
     * @param i
     * @returns {google.maps.Marker}
     */
    showNumberMarkOnRouter(routerId)
    {
            let routerPointsInfo = OBJECT.directionsDisplay[routerId].getDirections();
            let route = routerPointsInfo.routes[0];
            let markerCounter=0;
            this.addMarkerOnRouter(route.legs[0].start_location, markerCounter++, routerId);

            for (let i = 0; i < route.legs.length; i++) {
                this.addMarkerOnRouter(route.legs[i].start_location, markerCounter++ , routerId);

            }

    }

    /**
     * 司机是否已经分配了
     * @param driverId
     * @returns {boolean}
     * @constructor
     */
    DriverIsAssign( driverId)
    {
        for( let routerId in OBJECT.routerPonits)
        {
            if( OBJECT.routerPonits[routerId].driverId == driverId )
            {
                return true;
            }
        }
        return false;
    }


}